<?php
/**
 * @copyright   Copyright (c) 2017 https://www.sapixx.com All rights reserved.
 * @license     Licensed (http://www.apache.org/licenses/LICENSE-2.0).
 * @author      pillar<ltmn@qq.com>
 * 支付回调通知
 */
namespace app\allwin\controller\api\v4;
use app\allwin\model\AllwinConfig;
use app\allwin\model\AllwinShopCoupon;
use app\allwin\model\CouponUser;
use app\common\event\User;
use app\common\facade\Inform;
use app\common\facade\WechatPay;
use app\allwin\controller\api\Base;
use app\allwin\model\AllwinShop;
use app\allwin\model\AllwinShopOrder;
use app\allwin\model\Bank;
use app\allwin\model\BankBill;
use filter\Filter;
use Exception;

class Shopnotify extends Base{

    /**
     * 购买商品通知
     * @return void
     */
    public function index(){
        try{
            $response = WechatPay::doPay($this->miniapp_id)->handlePaidNotify(function ($message,$fail) {
                $result = AllwinShopOrder::where(['status'=>0,'paid_at'=>0,'is_del'=>0,'order_no' => Filter::filter_escape($message['out_trade_no'])])->find();
                if (empty($result)) {
                    return true;
                }
                if ($message['return_code'] === 'SUCCESS') {
                    if ($message['result_code'] === 'SUCCESS') {
                        $sub_mchid  = $message['sub_mch_id'] ?? '';
                        $ispay = WechatPay::doPay($this->miniapp_id,false,$sub_mchid)->order->queryByOutTradeNumber($result->order_no);
                        if ($ispay['return_code'] === 'SUCCESS') {
                            if ($ispay['result_code'] === 'SUCCESS') {
                                if ($ispay['trade_state'] === 'SUCCESS') {
                                    //修改订单状态和减少库存
                                    $result->paid_at   = 1;
                                    $result->paid_time = strtotime($ispay['time_end']);
                                    $result->paid_no   = $ispay['transaction_id'];
                                    $result->save();
                                    AllwinShop::where(['id' => $result->shop_id])->setDec('warehouse_num',1);  //减库存
                                    //减去所用积分
                                    if($result['points']){
                                        $bank = Bank::where(['member_miniapp_id'=>$this->miniapp_id,'user_id' => $result->user_id])->find();
                                        $bank->shop_money  = $bank->shop_money - $result->points;
                                        $bank->update_time = time();
                                        $bank->save();
                                    }
                                    //商品信息
                                    $shopItme = AllwinShop::where(['member_miniapp_id'=>$this->miniapp_id,'id' => $result['shop_id']])->find();
                                    $allMoney = money(($ispay['total_fee'] - $ispay['total_fee'] * 6 / 1000) / 100);
                                    $prorateMoney = $allMoney;
                                     //发放分享收益
                                    if($result['share_uid']){
                                        $money =  money($shopItme['sell_price'] * $shopItme['share_price'] /100);
                                        $prorateMoney -= $money;
                                        if($prorateMoney >= 0){
                                            Bank::recharge($this->miniapp_id,$result['share_uid'],$money);
                                            Inform::sms($result['share_uid'],$this->miniapp_id,['title' =>'业务进展通知','type' => '奖励发放','content' =>'您有一条新的订单奖励已到账']);
                                            BankBill::add(['miniapp_id'=>$this->miniapp_id,'store_id' => 0,'money' => $money,'uid'=>$result['share_uid'],'pay_uid' => 0], '分享商品收益');
                                        }

                                    }
                                    //发放经纪人收益
                                    if($shopItme['detective_uid']){
                                        $money =  money($shopItme['sell_price'] * $shopItme['detective_price'] /100);
                                        $prorateMoney -= $money;
                                       if($prorateMoney >= 0){
                                           Bank::recharge($this->miniapp_id,$shopItme['detective_uid'],$money);
                                           Inform::sms($shopItme['detective_uid'],$this->miniapp_id,['title' =>'业务进展通知','type' => '奖励发放','content' =>'您有一条新的订单奖励已到账']);
                                           BankBill::add(['miniapp_id'=>$this->miniapp_id,'store_id' => 0,'money' => $money,'uid'=>$shopItme['detective_uid'],'pay_uid' => 0], '经济人收益');
                                       }
                                    }
                                    //增加日志
                                    BankBill::add(['miniapp_id'=>$this->miniapp_id,'store_id' => $result->store_id,'money' => -$result->amount,'uid'=>$result->user_id,'pay_uid' => $result->user_id], '微信支付[购买商品]');
                                    //增加积分
                                    Bank::rePoints($this->miniapp_id, $result->user_id,intval($result->amount));
                                    //申请者微信通知
                                    Inform::sms($result->user_id,$this->miniapp_id,['title' =>'业务进展通知','type' => '新订单','content' =>'您有一条新的订单信息']);
                                    //后台管理员微信通知
                                    Inform::sms(User::isFounder($this->miniapp_id)->user_id,$this->miniapp_id,['title' =>'业务进展通知','type' => '新订单','content' =>'您有一条新的订单信息']);
                                    AllwinShopOrder::income($result->toArray(),$allMoney,$prorateMoney);
                                    if($shopItme->warehouse_num >= 0){
                                        $shopItme->warehouse_num = $shopItme->warehouse_num - 1;
                                        $shopItme->save();
                                    }
                                    //赠送优惠券
                                    CouponUser::addUserCoupon(json_encode(AllwinShopCoupon::where(['member_miniapp_id'=>$this->miniapp_id,'shop_id' => $result['shop_id']])->column('coupon_id')),$this->user->id);
                                    return true;
                                }
                            }
                        }
                    }
                }
                return $fail('通信失败,请稍后再通知我');
            });
            $response->send();
        }catch (Exception $e) {
            $this->error('页面不存在');
        }
    }
}